package kr.ac.ml.mvc;

import java.net.URLEncoder;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpUtil {

	public static void forward(HttpServletRequest request, HttpServletResponse response, String path ) {
		try{
			String mobile = request.getParameter("mobile");
			if("1".equals(mobile)){
				path = path.replace(".jsp", "_m.jsp");
			}
			System.out.println( path );
			RequestDispatcher dispatcher = request.getRequestDispatcher(path);
			dispatcher.forward(request, response);

		} catch( Exception ex ) {
			throw new RuntimeException( "forward Exception : " + ex);
		}
	}

	public static void redirect(
			HttpServletRequest request, 
			HttpServletResponse response, 
			String path ){
		try{
			String mobile = request.getParameter("mobile");
			if( "1".equals(mobile) ){
				path = path + ( path.contains("?") ? "&mobile=1" : "?mobile=1" );
			}
			response.sendRedirect( path );
		} catch( Exception ex ) {
			throw new RuntimeException("redirect 오류  : " + ex);
		}
	}

	public static String encoding( String url, String charset ){
		try{
			url = URLEncoder.encode( url, charset );
		}catch(Exception ex){
			throw new RuntimeException("URL 인코딩 시  오류 : " + ex);			
		}

		return url;
	}
}
